[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { PageContentFooter } from '~/components/PageContentFooter';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { EditorConfig } from '~/interfaces/editor-settings';
  26. import { CustomWindow } from '~/interfaces/global';
  27. import { RendererConfig } from '~/interfaces/services/renderer';
  28. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  29. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  30. import { PageModel, PageDocument } from '~/server/models/page';
  31. import { PageRedirectModel } from '~/server/models/page-redirect';
  32. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  33. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  34. import { useRedirectFrom } from '~/stores/page-redirect';
  35. import {
  36. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  37. } from '~/stores/ui';
  38. import loggerFactory from '~/utils/logger';
  39. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  40. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  41. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  42. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  43. import { BasicLayout } from '../components/Layout/BasicLayout';
  44. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  45. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  46. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  47. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  48. import {
  49. useCurrentUser, useCurrentPagePath,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useHackmdUri,
  55. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  58. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, usePageUser,
  59. } from '../stores/context';
  60. import {
  61. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  62. } from './utils/commons';
  63. // import { useCurrentPageSWR } from '../stores/page';
  64. import styles from './[[...path]].page.module.scss';
  65. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  66. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  67. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  69. const logger = loggerFactory('growi:pages:all');
  70. const {
  71. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  72. } = pagePathUtils;
  73. const { removeHeadingSlash } = pathUtils;
  74. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  75. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  76. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  77. {
  78. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  79. return v?.data != null
  80. && v?.data.toObject != null
  81. && v?.meta != null
  82. && isIPageInfoForEntity(v.meta);
  83. },
  84. serialize: (v) => {
  85. return {
  86. data: superjson.stringify(v.data.toObject()),
  87. meta: superjson.stringify(v.meta),
  88. };
  89. },
  90. deserialize: (v) => {
  91. return {
  92. data: superjson.parse(v.data),
  93. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  94. };
  95. },
  96. },
  97. 'IPageToShowRevisionWithMetaTransformer',
  98. );
  99. const IdenticalPathPage = (): JSX.Element => {
  100. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  101. return <IdenticalPathPage />;
  102. };
  103. const PutbackPageModal = (): JSX.Element => {
  104. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  105. return <PutbackPageModal />;
  106. };
  107. type Props = CommonProps & {
  108. currentUser: IUser,
  109. pageWithMeta: IPageToShowRevisionWithMeta,
  110. // pageUser?: any,
  111. redirectFrom?: string;
  112. // shareLinkId?: string;
  113. isLatestRevision?: boolean
  114. isIdenticalPathPage?: boolean,
  115. isForbidden: boolean,
  116. isNotFound: boolean,
  117. IsNotCreatable: boolean,
  118. // isAbleToDeleteCompletely: boolean,
  119. isSearchServiceConfigured: boolean,
  120. isSearchServiceReachable: boolean,
  121. isSearchScopeChildrenAsDefault: boolean,
  122. isSlackConfigured: boolean,
  123. // isMailerSetup: boolean,
  124. isAclEnabled: boolean,
  125. // hasSlackConfig: boolean,
  126. // drawioUri: string,
  127. hackmdUri: string,
  128. // noCdn: string,
  129. // highlightJsStyle: string,
  130. isAllReplyShown: boolean,
  131. // isContainerFluid: boolean,
  132. editorConfig: EditorConfig,
  133. isEnabledStaleNotification: boolean,
  134. // isEnabledLinebreaks: boolean,
  135. // isEnabledLinebreaksInComments: boolean,
  136. // adminPreferredIndentSize: number,
  137. // isIndentSizeForced: boolean,
  138. disableLinkSharing: boolean,
  139. rendererConfig: RendererConfig,
  140. // UI
  141. userUISettings?: IUserUISettings
  142. // Sidebar
  143. sidebarConfig: ISidebarConfig,
  144. };
  145. const GrowiPage: NextPage<Props> = (props: Props) => {
  146. // const { t } = useTranslation();
  147. const router = useRouter();
  148. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  149. // register global EventEmitter
  150. if (isClient()) {
  151. (window as CustomWindow).globalEmitter = new EventEmitter();
  152. }
  153. // commons
  154. useEditorConfig(props.editorConfig);
  155. useCsrfToken(props.csrfToken);
  156. // UserUISettings
  157. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  158. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  159. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  160. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  161. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotFound(props.isNotFound);
  167. useIsNotCreatable(props.IsNotCreatable);
  168. useRedirectFrom(props.redirectFrom);
  169. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  170. // useShared();
  171. // useShareLinkId(props.shareLinkId);
  172. useIsSharedUser(false); // this page cann't be routed for '/share'
  173. useIsIdenticalPath(false); // TODO: need to initialize from props
  174. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  175. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. // useDrawioUri(props.drawioUri);
  184. useHackmdUri(props.hackmdUri);
  185. // useNoCdn(props.noCdn);
  186. // useIndentSize(props.adminPreferredIndentSize);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. useIsAllReplyShown(props.isAllReplyShown);
  192. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  193. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  194. // const { data: editorMode } = useEditorMode();
  195. const { pageWithMeta, userUISettings } = props;
  196. let shouldRenderPutbackPageModal = false;
  197. if (pageWithMeta != null) {
  198. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  199. }
  200. const pageId = pageWithMeta?.data._id;
  201. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  202. useCurrentPageId(pageId);
  203. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  204. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  205. useIsTrashPage(_isTrashPage(pagePath));
  206. useIsUserPage(isUserPage(pagePath));
  207. useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  208. useCurrentPagePath(pagePath);
  209. useCurrentPathname(props.currentPathname);
  210. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  211. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  212. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  213. usePageUser(pageWithMeta?.data.creator);
  214. // sync grant data
  215. useEffect(() => {
  216. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  217. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  218. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  219. useEffect(() => {
  220. const decodedURI = decodeURI(window.location.pathname);
  221. if (isClient() && decodedURI !== props.currentPathname) {
  222. router.replace(props.currentPathname, undefined, { shallow: true });
  223. }
  224. }, [props.currentPathname, router]);
  225. const classNames: string[] = [];
  226. // switch (editorMode) {
  227. // case EditorMode.Editor:
  228. // classNames.push('on-edit', 'builtin-editor');
  229. // break;
  230. // case EditorMode.HackMD:
  231. // classNames.push('on-edit', 'hackmd');
  232. // break;
  233. // }
  234. // if (page == null) {
  235. // classNames.push('not-found-page');
  236. // }
  237. return (
  238. <>
  239. <Head>
  240. {/*
  241. {renderScriptTagByName('drawio-viewer')}
  242. {renderScriptTagByName('highlight-addons')}
  243. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  244. */}
  245. </Head>
  246. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  247. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  248. <div className="h-100 d-flex flex-column justify-content-between">
  249. <header className="py-0 position-relative">
  250. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  251. </header>
  252. <div className="d-edit-none">
  253. <GrowiSubNavigationSwitcher />
  254. </div>
  255. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  256. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  257. <div className="flex-grow-1">
  258. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  259. <div id="content-main" className="content-main grw-container-convertible">
  260. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  261. { !props.isIdenticalPathPage && (
  262. <>
  263. <PageAlerts />
  264. { props.isForbidden && <ForbiddenPage /> }
  265. { props.IsNotCreatable && <NotCreatablePage />}
  266. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  267. {/* <DisplaySwitcher /> */}
  268. {/* <PageStatusAlert /> */}
  269. </>
  270. ) }
  271. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  272. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  273. <div id="revision-toc-content" className="revision-toc-content"></div>
  274. </div>
  275. </div> */}
  276. </div>
  277. </div>
  278. </div>
  279. {/* TODO: Check CSS import */}
  280. <footer className="footer d-edit-none">
  281. {/* TODO: Enable page_list.html */}
  282. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  283. {/* { !props.isIdenticalPathPage && ( */}
  284. <Comments pageId={pageId} />
  285. {/* )} */}
  286. {/* TODO: Create UsersHomePageFooter conponent */}
  287. { isUsersHomePage(props.currentPathname) && (
  288. <div className="container-lg user-page-footer py-5">
  289. <div className="grw-user-page-list-m d-edit-none">
  290. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  291. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  292. Bookmarks
  293. </h2>
  294. <div id="user-bookmark-list" className={`page-list ${styles['page-list']}`}>
  295. {/* TODO: No need page-list-container class ? */}
  296. <div className="page-list-container">
  297. {/* <BookmarkList userId={pageContainer.state.creator._id} /> */}
  298. </div>
  299. </div>
  300. </div>
  301. <div className="grw-user-page-list-m mt-5 d-edit-none">
  302. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  303. <i id="recent-created-icon" className="mr-1">
  304. {/* <RecentlyCreatedIcon /> */}
  305. </i>
  306. Recently Created
  307. </h2>
  308. <div id="user-created-list" className={`page-list ${styles['page-list']}`}>
  309. {/* TODO: No need page-list-container class ? */}
  310. <div className="page-list-container">
  311. {/* <RecentCreated userId={pageContainer.state.creator._id} /> */}
  312. </div>
  313. </div>
  314. </div>
  315. </div>
  316. )}
  317. <PageContentFooter />
  318. </footer>
  319. <UnsavedAlertDialog />
  320. <DescendantsPageListModal />
  321. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  322. </div>
  323. </BasicLayout>
  324. </>
  325. );
  326. };
  327. function getPageIdFromPathname(currentPathname: string): string | null {
  328. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  329. }
  330. class MultiplePagesHitsError extends ExtensibleCustomError {
  331. pagePath: string;
  332. constructor(pagePath: string) {
  333. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  334. this.pagePath = pagePath;
  335. }
  336. }
  337. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  338. const req: CrowiRequest = context.req as CrowiRequest;
  339. const { crowi } = req;
  340. const { revisionId } = req.query;
  341. const Page = crowi.model('Page') as PageModel;
  342. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  343. const { pageService } = crowi;
  344. let currentPathname = props.currentPathname;
  345. const pageId = getPageIdFromPathname(currentPathname);
  346. const isPermalink = _isPermalink(currentPathname);
  347. const { user } = req;
  348. if (!isPermalink) {
  349. // check redirects
  350. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  351. if (chains != null) {
  352. // overwrite currentPathname
  353. currentPathname = chains.end.toPath;
  354. props.currentPathname = currentPathname;
  355. // set redirectFrom
  356. props.redirectFrom = chains.start.fromPath;
  357. }
  358. // check whether the specified page path hits to multiple pages
  359. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  360. if (count > 1) {
  361. throw new MultiplePagesHitsError(currentPathname);
  362. }
  363. }
  364. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  365. const page = pageWithMeta?.data as unknown as PageDocument;
  366. // populate & check if the revision is latest
  367. if (page != null) {
  368. page.initLatestRevisionField(revisionId);
  369. await page.populateDataToShowRevision();
  370. props.isLatestRevision = page.isLatestRevision();
  371. }
  372. props.pageWithMeta = pageWithMeta;
  373. }
  374. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  375. const req = context.req as CrowiRequest<IUserHasId & any>;
  376. const { user } = req;
  377. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  378. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  379. if (userUISettings != null) {
  380. props.userUISettings = userUISettings.toObject();
  381. }
  382. }
  383. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  384. const req: CrowiRequest = context.req as CrowiRequest;
  385. const { crowi } = req;
  386. const Page = crowi.model('Page') as PageModel;
  387. const { currentPathname } = props;
  388. const pageId = getPageIdFromPathname(currentPathname);
  389. const isPermalink = _isPermalink(currentPathname);
  390. const page = props.pageWithMeta?.data;
  391. if (props.isIdenticalPathPage) {
  392. // TBD
  393. }
  394. else if (page == null) {
  395. props.isNotFound = true;
  396. props.IsNotCreatable = !isCreatablePage(currentPathname);
  397. // check the page is forbidden or just does not exist.
  398. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  399. props.isForbidden = count > 0;
  400. }
  401. else {
  402. props.isNotFound = page.isEmpty;
  403. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  404. if (isPermalink && page.isEmpty) {
  405. props.currentPathname = page.path;
  406. }
  407. // /path/to/page ==> /62a88db47fed8b2d94f30000
  408. if (!isPermalink && !page.isEmpty) {
  409. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  410. if (!isToppage) {
  411. props.currentPathname = `/${page._id}`;
  412. }
  413. }
  414. }
  415. }
  416. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  417. // const req: CrowiRequest = context.req as CrowiRequest;
  418. // const { crowi } = req;
  419. // const UserModel = crowi.model('User');
  420. // if (isUserPage(props.currentPagePath)) {
  421. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  422. // if (user != null) {
  423. // props.pageUser = JSON.stringify(user.toObject());
  424. // }
  425. // }
  426. // }
  427. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  428. const req: CrowiRequest = context.req as CrowiRequest;
  429. const { crowi } = req;
  430. const {
  431. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  432. } = crowi;
  433. props.isSearchServiceConfigured = searchService.isConfigured;
  434. props.isSearchServiceReachable = searchService.isReachable;
  435. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  436. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  437. // props.isMailerSetup = mailService.isMailerSetup;
  438. props.isAclEnabled = aclService.isAclEnabled();
  439. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  440. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  441. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  442. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  443. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  444. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  445. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  446. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  447. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  448. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  449. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  450. props.editorConfig = {
  451. upload: {
  452. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  453. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  454. },
  455. };
  456. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  457. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  458. props.rendererConfig = {
  459. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  460. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  461. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  462. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  463. plantumlUri: process.env.PLANTUML_URI ?? null,
  464. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  465. // XSS Options
  466. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  467. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  468. tagWhiteList: crowi.xssService.getTagWhiteList(),
  469. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  470. };
  471. props.sidebarConfig = {
  472. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  473. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  474. };
  475. }
  476. /**
  477. * for Server Side Translations
  478. * @param context
  479. * @param props
  480. * @param namespacesRequired
  481. */
  482. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  483. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  484. props._nextI18Next = nextI18NextConfig._nextI18Next;
  485. }
  486. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  487. const req = context.req as CrowiRequest<IUserHasId & any>;
  488. const { user } = req;
  489. const result = await getServerSideCommonProps(context);
  490. // check for presence
  491. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  492. if (!('props' in result)) {
  493. throw new Error('invalid getSSP result');
  494. }
  495. const props: Props = result.props as Props;
  496. if (props.redirectDestination != null) {
  497. return {
  498. redirect: {
  499. permanent: false,
  500. destination: props.redirectDestination,
  501. },
  502. };
  503. }
  504. if (user != null) {
  505. props.currentUser = user.toObject();
  506. }
  507. try {
  508. await injectPageData(context, props);
  509. }
  510. catch (err) {
  511. if (err instanceof MultiplePagesHitsError) {
  512. props.isIdenticalPathPage = true;
  513. }
  514. else {
  515. throw err;
  516. }
  517. }
  518. await injectUserUISettings(context, props);
  519. await injectRoutingInformation(context, props);
  520. injectServerConfigurations(context, props);
  521. await injectNextI18NextConfigurations(context, props, ['translation']);
  522. return {
  523. props,
  524. };
  525. };
  526. export default GrowiPage;